package edu.gxmzu.task.config.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.gxmzu.task.entity.Accounts;
import edu.gxmzu.task.mapper.AccountsMapper;
import edu.gxmzu.task.mapper.UserInfoMapper;
import edu.gxmzu.task.utils.ConvertMyUserDetailsUtil;
import edu.gxmzu.task.utils.RedisService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private AccountsMapper accountsMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private RedisService redisService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        Accounts account;
        log.info("开始认证");
        Object object = redisService.getValue(RedisService.USER_KEY + username);
        if (Objects.isNull(object)) {
            log.info("数据库加载。。。");
            LambdaQueryWrapper<Accounts> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Accounts::getDeletionState, 0);
            wrapper.eq(Accounts::getUsername, username)
                    .or()
                    .eq(Accounts::getEmail, username);
            account = accountsMapper.selectOne(wrapper);
        }else {
            log.info("缓存加载。。。");
            MyUserDetails myUserDetails = ConvertMyUserDetailsUtil.convert(object);
            account = myUserDetails.getAccount();
        }
        log.info("account:" + account);
        if (Objects.isNull(account) || account.getDeletionState() != 0) throw new UsernameNotFoundException("用户不存在!");
        // 查询授权信息
        List<String> roles = userInfoMapper.selectRolesByUserId(account.getUserId());
        log.info("认证成功");
        log.info("roles:" + roles);
        // 封装UserDetails
        return new MyUserDetails(account, roles);
    }
}
